﻿using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using com.tdb.posion.protocol.protobuf;
using UnityEngine.Events;

/// <summary>
/// 描 述：
/// author： 
/// </summary>
public class UdpHelper
{

    public UdpHelper(UnityAction<byte[], IPEndPoint> dataCallback)
    {
        _listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        _listenerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
        _onDataArriveCallback = dataCallback;
    }
    
    /// <summary>
    /// udp的消息接收接口
    /// </summary>
    private Socket _listenerSocket = null;
    /// <summary>
    /// 数据到达时的回调
    /// </summary>
    private UnityAction<byte[], IPEndPoint> _onDataArriveCallback;
    
    

    /// <summary>
    /// 发送Message
    /// </summary>
    public void SendMessage(byte[] data, IPEndPoint target)
    {
        using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
        {
            s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
            s.SendTo(data, target);
        }
    }

    
    /// <summary>
    /// 接受UDP信息
    /// </summary>
    /// <returns></returns>
    public IEnumerator ListenUdpMsg()
    {
        var host = new IPEndPoint(IPAddress.Any, Const.UdpListenerPort);
        _listenerSocket.Bind(host);
        byte[] data = new byte[4096];
        EndPoint listenerEp = new IPEndPoint(IPAddress.Any, Const.UdpListenerPort);
        while (true)
        {
            if(_listenerSocket.Available>0)
            {
                _listenerSocket.ReceiveFrom(data, ref listenerEp);
                IPEndPoint remoteEndPoint = listenerEp as IPEndPoint;
                if (remoteEndPoint.Address.ToString().Equals(NetUtil.GetLocalIp()))
                {
                    continue;
                }

                _onDataArriveCallback(NetUtil.ReadMsgWithFixedLength(data), remoteEndPoint);
//                Message msg = Message.CreateBuilder().MergeFrom(.Build();
//                Debug.Log("Receive From :"+listenerEp+" Message :"+msg);
            }
            yield return null;
        }
    }

    /// <summary>
    /// 关闭udp的Socket
    /// </summary>
    public void Close()
    {
        if (_listenerSocket != null)
        {
            _listenerSocket.Shutdown(SocketShutdown.Both);
            _listenerSocket.Close();
            _listenerSocket = null;
        }
    }
}